using Castle.MicroKernel;
using NHibernate;
using NHibernate.Type;

namespace NDomain.ExampleModels.BloggingSystem.Infrastructure
{
    public class NHibernateInterceptor : EmptyInterceptor
    {
        public IKernel container;

        public NHibernateInterceptor(IKernel blogRepository)
        {
            container = blogRepository;
        }

        public override bool OnLoad(object entity, object id, object[] state, string[] propertyNames, IType[] types)
        {
            IoCHelper.InjectDependencies(entity, container);
            return false;
        }

        public override object IsUnsaved(object entity)
        {
            return entity is NullObject ? false : base.IsUnsaved(entity);
        }

        public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types)
        {
            return Nullize(state);
        }

        public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types)
        {
            return Nullize(currentState);
        }

        private static bool Nullize(object[] currentState)
        {
            bool stateChanged = false;
            for (int i = 0; i < currentState.Length; i++)
                if (currentState[i] is NullObject)
                {
                    currentState[i] = null;
                    stateChanged = true;
                }
            return stateChanged;
        }

        public override int[] FindDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types)
        {
            return entity is NullObject ? new int[0] : base.FindDirty(entity, id, currentState, previousState, propertyNames, types);
        }
    }
}